<template>
  <el-drawer :model-value="modelValue" :title="drawerTitle" :size="1000" :close-on-click-modal="false" destroy-on-close
    :before-close="handleBeforeClose" @update:model-value="handleDrawerClose">

    <div class="h-[75vh]">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="auto">
        <!-- 基本信息 -->
        <div class="flex mb-[2px]">
          <el-form-item :label="$t('competition.competitionName')" prop="title" class="flex-1  ml-5">
            <el-input v-model="formData.title" :placeholder="$t('common.inputPhTxt')" maxlength="50" />
          </el-form-item>
          <el-form-item :label="$t('competition.competitionType')" prop="matchType" class="flex-1">
            <el-radio-group v-model="formData.matchType">
              <el-radio v-for="item in competitionTypes" :key="item.value" :value="item.value">
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </div>

        <!-- 大赛简介 -->
        <el-form-item :label="$t('competition.competitionIntroduction')" prop="introduction" class="ml-5 mb-5">
          <el-input v-model="formData.introduction" :rows="4" type="textarea" :placeholder="$t('common.inputPhTxt')"
            maxlength="1000" show-word-limit />
        </el-form-item>

        <!-- 图片上传 -->
        <div class="flex mb-[2px]">
          <el-form-item :label="$t('competition.dynamicCover')" prop="cover" class="flex-1  ml-5">
            <div class="text-[#aeaeae] text-xs mb-[15px] mt-[6px]">{{ $t('competition.uploadTips.dynamicCoverTip', { formats: 'png、jpeg、jpg', dimensions: '1920x360px', size: '10' }) }}</div>
            <ImageListUpload :stemImages="coverImages" :imgNumber="1" :limit-size-img="10"
              @update:stemImages="handleCoverUpdate" :actionImgStyle="`width: 364px; height: 64px;`"  />
          </el-form-item>
          <el-form-item :label="$t('competition.customerQrCode')" prop="customerQuickCode" class="flex-1">
            <div class="text-[#aeaeae] text-xs mb-[15px] mt-[6px]">{{ $t('competition.uploadTips.dynamicCoverTip', { formats: 'png、jpeg、jpg', dimensions: '246x138px', size: '10' }) }}</div>
            <ImageListUpload :stemImages="qrCodeImages" :imgNumber="1" :limit-size-img="10"
              @update:stemImages="handleQrCodeUpdate" />
          </el-form-item>
        </div>

        <!-- 视频上传 -->
        <el-form-item :label="$t('competition.homeIntroVideo')" class="ml-5 mb-5">
          <div class="text-[#aeaeae] text-xs mb-[15px] mt-[8px] w-full">{{ $t('competition.uploadTips.videoTip', { duration: '20min', format: 'MP4', ratio: '16:9', size: '500M' }) }}</div>
          <div class="w-[370px]">
            <UploadVideo ref="uploadVideoRef" v-model="formData.introduceVideo" :delete-remote="false"
              style-preview="width: 400px;height: 300px;">
              <template #upload-btn>
                <div
                  class="w-[364px] h-[204px] border border-gray-300 rounded flex flex-col items-center justify-center cursor-pointer transition-all duration-300 hover:border-blue-500 hover:text-blue-500">
                  <Film class="text-xl mb-1 w-8 h-8 text-[#595959]" />
                  <div class="text-xs text-gray-600">{{ $t('competition.uploadVideo') }}</div>
                </div>
              </template>
            </UploadVideo>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="flex justify-end gap-3">
        <el-button @click="handleCancel">{{ $t('common.cancelTxt') }}</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="loading">
          {{ $t('competition.confirm') }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { $t } from '@vben/locales';
import deleteIcon from '#/assets/images/delete-icon.png';
import type { FormInstance, FormRules } from 'element-plus';
import { Film } from '@vben/icons'
import ImageListUpload from "#/components/common/image-list-upload.vue"
import UploadVideo from "#/components/common/upload-video.vue"
import { createMatchManageApi } from '#/api/competition/competition-list';

// 类型定义
interface Props {
  modelValue: boolean;
  formData: any;
  mode: 'add' | 'edit';
  competitionTypes: any[];
}

interface FormData {
  id?: string;
  title: string;
  introduction: string;
  matchType: string;
  cover: string;
  customerQuickCode: string;
  introduceVideo: string;
}

const props = defineProps<Props>();
const emit = defineEmits<{
  'update:modelValue': [value: boolean];
  success: [actionType: string];
  cancel: [];
}>();

// 引用
const formRef = ref<FormInstance>();
const uploadVideoRef = ref<InstanceType<typeof UploadVideo> | null>(null);

// 响应式数据
const formData = ref<FormData>({
  title: '',
  introduction: '',
  matchType: '',
  cover: '',
  customerQuickCode: '',
  introduceVideo: '',
});
const originalFormData = ref<FormData>({} as FormData);
const loading = ref(false);
const isProcessing = ref(false);
const isSuccessClose = ref(false);

// 计算属性
const drawerTitle = computed(() =>
  props.mode === 'add' ? $t('competition.newCompetition') : $t('competition.editCompetition')
);

const isFormChanged = computed(() => {
  if (!formData.value || !originalFormData.value) return false;
  return JSON.stringify(formData.value) !== JSON.stringify(originalFormData.value);
});

const coverImages = computed(() =>
  formData.value.cover ? [{ id: 'cover', path: formData.value.cover }] : []
);

const qrCodeImages = computed(() =>
  formData.value.customerQuickCode ? [{ id: 'customerQuickCode', path: formData.value.customerQuickCode }] : []
);

// 表单验证规则
const rules: FormRules = {
  title: [{ required: true, message: $t('competition.validationName'), trigger: 'blur' }],
  matchType: [{ required: true, message: $t('competition.validationType'), trigger: 'change' }],
  cover: [{ required: true, message: $t('competition.uploadDynamicCover'), trigger: 'change' }],
  customerQuickCode: [{ required: true, message: $t('请上传大赛封面'), trigger: 'change' }],
};

// 事件处理函数
const handleCoverUpdate = (images: any[]) => {
  formData.value.cover = images[0]?.path || '';
  // 上传后清除该字段的验证提示
  formRef.value?.clearValidate('cover');
};

const handleQrCodeUpdate = (images: any[]) => {
  formData.value.customerQuickCode = images[0]?.path || '';
  // 上传后清除该字段的验证提示
  formRef.value?.clearValidate('customerQuickCode');
};

const handleDrawerClose = (value: boolean) => {
  emit('update:modelValue', value);
};

// 初始化表单数据
const initFormData = (data: any) => {
  const newData = JSON.parse(JSON.stringify(data));
  // 确保必要字段存在
  newData.customerQuickCode = newData.customerQuickCode || '';
  newData.introduceVideo = newData.introduceVideo || '';
  return newData;
};

// 监听props数据变化
watch(() => props.formData, (val: any) => {
  if (val && Object.keys(val).length > 0) {
    formData.value = initFormData(val);
    originalFormData.value = initFormData(val);
    isProcessing.value = false;
    isSuccessClose.value = false;
  }
}, { immediate: true, deep: true });

// API调用
const submitForm = async () => {
  const { id, title, introduction, matchType, cover, customerQuickCode, introduceVideo } = formData.value;

  await createMatchManageApi({
    id,
    title,
    introduction,
    matchType,
    cover,
    customerQuickCode,
    introduceVideo,
    status: 1,
  });

  ElMessage.success(props.mode === 'add' ? $t('competition.addSuccessMsg') : $t('competition.updateSuccessMsg'));
  isSuccessClose.value = true;
  emit('update:modelValue', false);
  emit('success', 'confirm');
};

// 确定按钮事件
const handleConfirm = async () => {
  if (!formRef.value) {
    ElMessage.warning($t('competition.incompleteInfo'));
    return;
  }

  if (uploadVideoRef.value?.isUploading) {
    ElMessage.warning($t('competition.waitVideoUpload'));
    return;
  }

  try {
    await formRef.value.validate();
    loading.value = true;
    isProcessing.value = true;
    await submitForm();
  } catch (error) {
    // 移除 console.error 调试语句
  } finally {
    loading.value = false;
    isProcessing.value = false;
  }
};

// 显示确认退出对话框
const showExitConfirm = async (): Promise<boolean> => {
  try {
    await ElMessageBox.confirm('', {
      title: '',
      message: `
        <div style="display: flex; align-items: center;">
          <img src="${deleteIcon}" style="width: 48px; height: 48px; margin-right: 10px;" />
          <span>${$t('competition.dataNotSavedConfirmExit')}</span>
        </div>
      `,
      confirmButtonText: $t('competition.yes'),
      cancelButtonText: $t('competition.no'),
      customClass: 'delete-dialog',
      dangerouslyUseHTMLString: true,
      center: false,
      distinguishCancelAndClose: true,
    });
    return true; // 用户选择"是"，确认退出
  } catch (error) {
    return false; // 用户选择"否"或关闭对话框，不退出
  }
};

// 检查是否可以关闭
const checkCanClose = async (): Promise<boolean> => {
  if (isProcessing.value) return false;

  // 如果表单有修改且不是成功关闭，显示确认对话框
  if (isFormChanged.value && !isSuccessClose.value) {
    return await showExitConfirm();
  }

  return true; // 无修改，可以直接关闭
};

// 重置表单状态
const resetFormState = () => {
  isProcessing.value = false;
  loading.value = false;
  formRef.value?.resetFields();
};

// 处理抽屉关闭前的检查
const handleBeforeClose = async (done: () => void) => {
  try {
    const canClose = await checkCanClose();
    if (canClose) {
      resetFormState();
      emit('cancel');
      done();
    }
  } catch (error) {
    // 移除 console.error 调试语句
    resetFormState();
    emit('cancel');
    done();
  }
};

// 取消按钮事件
const handleCancel = async () => {
  try {
    const canClose = await checkCanClose();
    if (canClose) {
      resetFormState();
      emit('update:modelValue', false);
      emit('cancel');
    }
  } catch (error) {
    // 移除 console.error 调试语句
    resetFormState();
    emit('update:modelValue', false);
    emit('cancel');
  }
};
</script>
